package cn.dyw.engine.core.order;

import cn.dyw.engine.core.context.ReportStandardContext;

import java.util.List;

/**
 * mysql 排序渲染
 *
 * @author dyw770
 * @since 2021-08-09
 */
public class MysqlSortRender implements ISortRender {

    private final static String ORDER_BY_KEY_WORD = "order by";

    @Override
    public String sortRender(String sql, ReportStandardContext context) {

        // TODO 后面实现比较优雅的方式
        // 简单实现mysql中的排序机制
        StringBuilder sqlBuilder = new StringBuilder(sql);
        List<ExecSort> sorts = context.getSorts();
        if (!sorts.isEmpty()) {
            sqlBuilder.append(" ")
                    .append(ORDER_BY_KEY_WORD);
        }

        for (int i = 0; i < sorts.size(); i++) {
            ExecSort sort = sorts.get(i);
            sqlBuilder.append(" ")
                    .append(sort.getFieldName())
                    .append(" ")
                    .append(sort.getOrderType());

            if (i + 1 < sorts.size()) {
                sqlBuilder.append(",");
            }
        }
        return sqlBuilder.toString();
    }
}
